﻿using System;

namespace GGFramework.Core.Timer
{
    public class LoopTimer :TimerBase
    {
        public Action<int> OnLoopComplete;
        private float loopDuration;

        public LoopTimer() : base(0){ }

        public void Init(float duration, int loops = -1)
        {
            loopDuration = duration;
            Duration = duration;
            LoopCount = loops;
            RemainingTime = duration;
        }

        public override void Update(float deltaTime)
        {
            base.Update(deltaTime);

            if (RemainingTime <= 0)
            {
                currentLoop++;
                Complete();
                OnLoopComplete?.Invoke(currentLoop);

                if (LoopCount > 0 && currentLoop >= LoopCount)
                {
                    IsCompleted = true;
                    return;
                }

                RemainingTime = loopDuration;
            }
        }

        public override bool IsExpired => IsCompleted;
        
        public override void Cancel()
        {
            IsCompleted = true;
        }
    }
}